﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows;

namespace Netnr.CodeBuilder.Core
{
    class ConnectionTo
    {
        /// <summary>
        /// 得到拼接的连接字符串
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <param name="ErrorMessage">错误信息</param>
        /// <param name="SuccessResult">正确的信息</param>
        /// <returns></returns>
        public static bool JoinConnection(MainWindow mainWindow, out string ErrorMessage, out string SuccessResult)
        {
            bool b = true;
            string error = string.Empty;
            string sqlConn = string.Empty;
            string txt_server = mainWindow.Con_Txt_Server.Text;
            string txt_user = mainWindow.Con_Txt_User.Text;
            string txt_password = mainWindow.Con_Txt_Password.Text;
            string txt_database = mainWindow.Con_Cbx_Database.Text;

            if (txt_server == "" || txt_user == "" || txt_password == "")
            {
                b = false;
                error = "Field is required";
            }
            if (b)
            {
                sqlConn = string.Format("Server={0};Uid={1};Pwd={2};", txt_server, txt_user, txt_password);
                if (txt_database!="")
                {
                    sqlConn += "Database=" + txt_database;
                }
            }

            ErrorMessage = error;
            SuccessResult = sqlConn;
            return b;
        }
        public static string JoinConnection(MainWindow mainWindow)
        {
            string em = string.Empty;
            string sr = string.Empty;
            if (JoinConnection(mainWindow, out em, out sr))
            {
                return sr;
            }
            else
            {
                MessageBox.Show(em);
            }
            return string.Empty;
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="sqlConn"></param>
        /// <returns></returns>
        public static bool TestConnection(string sqlConn)
        {
            bool b = false;
            using (SqlConnection conn = new SqlConnection(sqlConn))
            {
                try
                {
                    conn.Open();
                    b = true;
                }
                catch (Exception)
                {

                }
                finally
                {
                    conn.Close();
                }
            }
            return b;
        }
    }
}
